/*
 * 新增交易跳转集群配置
 */
angular.module('inspinia',['uiSwitch',"ngJsTree",'angularFileUpload']).controller('jumpRouteAddCtrl',function($scope, $http,$timeout,FileUploader, $state,SweetAlert){
	
	$scope.groupList = [];//集群集合
	$scope.acqList = [];//收单机构集合
	$scope.baseInfo = {status:1, cardType:1, bpType:1,serviceTypeSelect:0, provinceType:0,monday:0,
			tuesday:1,wednesday:2,thursday:3,friday:4,saturday:5,sunday:6,cardBinType:0,acqMerchantState:0,acqMerchantShowState:0,
        	effectiveDateType:1,relationActivity:0,aiMatching:0};
	// $scope.bpTypeList = [{text:'不限',value:0},{text:'指定业务产品',value:1}];
	$scope.bpTypeList = [{text:'指定业务产品',value:1}];
	$scope.provinceTypeList = [{text:'不限',value:0},{text:'指定省份',value:1}];
	$scope.cardBinList = [{text:'不限',value:0},{text:'指定发卡行',value:1}];
	$scope.serviceTypeSelectList = [{text:'不限',value:0},{text:'指定服务类型',value:1}];
	$scope.acqMerchantList = [{text:'不限',value:0},{text:'指定行业',value:1}];
	$scope.effectiveDateTypeList = [{text:'每天',value:1},{text:'周一至周五',value:2},{text:'法定工作日',value:3},{text:'自定义',value:4}];
    $scope.statusList = [{text:"生效",value:1},{text:"失效",value:0}];

    //是否关联活动
	$scope.relationActivitySelect = [{text:"否",value:0},{text:"是",value:1}];
	$scope.relationActivityStr=angular.toJson($scope.relationActivitySelect);

	$scope.aiMatchingSelect = [{text:"开",value:1},{text:"关",value:0}];

	$scope.jumpId = 0;


	//改变业务产品时，需要切换省份表格的class，保证在切换业务产品的时候省份表格不挪位
	// $scope.changeBp = function(){
	// 	if($scope.baseInfo.bpType==0){
	// 		$scope.provinceClass = "col-sm-4";
	// 		angular.forEach($scope.bpGridApi.selection.getSelectedRows(),function(item,index){
	// 			$scope.bpGridApi.selection.unSelectRow(item);
	// 		})
	// 		$scope.baseInfo.serviceTypeSelect=0;
	// 		$scope.changeServiceTypeSelect();
	// 	} else {
	// 		$scope.provinceClass = "col-sm-1";
	// 	}
	// }
	//$scope.changeBp();
	
	//获取收单机构集合
	$http.post('routeGroup/acqOrgSelectBox.do'
	).success(function(data){
		$scope.acqList = data;
		for(var i=0;i<data.length;i++){
			if(data[i].acqName=="YS_ZQ"){
				$scope.acqMerchantShowStateId=data[i].id;
				break;
			}
		}
	});

	//获取所有的组织
    $http.get('teamInfo/queryTeamName.do').success(function(msg){
    	if(msg.status) {
            $scope.teamGrid.data = msg.teamInfo;
		}
    });
	
	//原来是‘获取所有包含POS刷卡服务的业务产品’，20171219修改为‘获取所有业务产品’
	$scope.getBpList = function() {
        var teamId = "";
		if($scope.teamGridApi) {
            var selectTeamList = $scope.teamGridApi.selection.getSelectedRows();
            if(selectTeamList != null && selectTeamList.length > 0) {
                angular.forEach(selectTeamList, function(item) {
                    teamId = teamId + item.teamId + ",";
                });
            }
		}
        $http.get("businessProductDefine/getProductByTeam?teamId=" + teamId).success(function(data){
            if(data.status){
                $scope.bpGrid.data = [];
                $scope.bpGrid.data = $scope.bpGridApi.selection.getSelectedRows();
                angular.forEach(data.bpList, function(item) {
					if(!existsBp(item.bpId, $scope.bpGrid.data)) {
                        $scope.bpGrid.data.push(item);
					}
				});
            }
        })
	};
    $scope.getBpList();

    /**
	 * 如果bpList包含bpId，返回true
     * @param bpId
     * @param bpList
     * @returns {boolean}
     */
    function existsBp(bpId, bpList){
    	var existsStatus = false;
    	if(bpList == null || bpList.length < 1) {
    		return existsStatus;
		}
        angular.forEach(bpList, function(item) {
			if(item.bpId == bpId) {
                existsStatus = true;
                return;
			}
        });
    	return existsStatus;
	}

	$scope.changeCardType = function(){
		if($scope.baseInfo.cardBinType=='0'){
			 $scope.acqMerchantClass = "col-sm-4";
		}else{
			$scope.getCardBinList();
			$scope.acqMerchantClass = "col-sm-1";
		}
	}
	$scope.changeCardType();

	$scope.testChange = function(){
		var s = $scope.cardServiceTypeGridApi.selection.getSelectedRows();
		console.log(s);
	}

	$scope.setAcqMerchantShowState=function(){
		if($scope.baseInfo.acqId==$scope.acqMerchantShowStateId){
			$scope.baseInfo.acqMerchantShowState=1;
		}else{
			$scope.baseInfo.acqMerchantShowState=0;
		}
	}

	$scope.getProvinceCityMultiselectList=[];
	$scope.getProvinceCityMultiselect = function() {
		if ($scope.getProvinceCityMultiselectList.length == 0) {
			$http.post('areaInfo/getProvinceCityMultiselect').success(function(result){
				if (result.data != null || result.data.length != 0) {
					angular.forEach(result.data,function(obj,index){
						$scope.getProvinceCityMultiselectList.push({text:obj.pname,value:obj.cname});
					});

					$timeout(function(){
						var tree3 = $("#provinceCity-treeMultiselect").treeMultiselect({
							enableSelectAll: true,
							searchable: true,
							sortable: true,
							startCollapsed: true,
							selectAllText: '全选',
							unselectAllText: '取消全选',
						});
					})
				}
			}).error(function(){

			});
		}
	}
	$scope.getProvinceCityMultiselect();

	//获取所有省份
	$scope.getAreaList=function(name,type,callback){
		if(name == null || name=="undefine"){
			return;
		}
		$http.post('areaInfo/getAreaByName','name='+name+'&&type='+type,
			{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
		).success(function(data){
			callback(data);
		}).error(function(){
		});
	}

	$scope.getCardBinList = function(){
		$http.post('jumpRoute/getCarBinList','cardType='+$scope.baseInfo.cardType,
			{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
		).success(function(data){
			$scope.cardBinGrid.data = data;
		}).error(function(){
		});
	}

	//获取收单机构
	$http.post('jumpRoute/getSysDictList',
		{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
	).success(function(data){
		$scope.acqMerchantGrid.data = data;
	});

	//获取商户服务类型为POS刷卡类的路由集群
	$http.get("routeGroup/getGroupByServiceType").success(function(data){
		if(data.status){
			angular.forEach(data.groupList,function(item){
				item.groupName = item.groupCode + " " + item.groupName;
			})
			$scope.groupList = data.groupList;
		}
	});

    //组织
    $scope.teamGrid = {
        columnDefs: [
            {field: 'teamName',displayName: '所属组织'},
        ],
        onRegisterApi : function(gridApi) {
            $scope.teamGridApi = gridApi;
            //行选中事件
            $scope.teamGridApi.selection.on.rowSelectionChanged($scope,function(row,event){
                $scope.getBpList();
            });
            //全选事件
            $scope.teamGridApi.selection.on.rowSelectionChangedBatch($scope,function(row,event){
                $scope.getBpList();
            });
        }
    };
	
	//业务产品（包含POS刷卡服务）表格
	$scope.bpGrid = {
	        columnDefs: [
	             {field: 'bpName',displayName: '业务产品'},
	        ],
			onRegisterApi : function(gridApi) {
				$scope.bpGridApi = gridApi;
			}
	};
	



	// TODO 服务类型
	$scope.bpIds=[];
	$scope.changeServiceTypeSelect = function(){
		$scope.bpIds=[];
		angular.forEach($scope.bpGridApi.selection.getSelectedRows(),function(item,index){
			$scope.bpIds[index] = item.bpId;
		})
		$http.post('jumpRoute/getServiceTypeSelect','bqIds='+angular.toJson($scope.bpIds),
				{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
			).success(function(data){
				$scope.serviceTypeGrid.data=data;
				$scope.cardServiceTypeGrid.data = [{"value":0,"sysName":"非优享"},{"value":1,"sysName":"优享"}];
		});
	};

	$scope.cardServiceTypeStatus = false;
	// 服务类型
	$scope.serviceTypeGrid = {
		columnDefs: [
		    {field: 'sysName',displayName: '服务类型'},
	    ],
		onRegisterApi : function(gridApi) {
			$scope.serviceTypeGridApi = gridApi;
			//行选中事件
			$scope.serviceTypeGridApi.selection.on.rowSelectionChanged($scope,function(row,event){
				if(row.isSelected){
					if($scope.serviceTypeGridApi.selection.getSelectedRows().length == 1){
						angular.forEach($scope.serviceTypeGridApi.selection.getSelectedRows(),function(item,index){
							if(item.sysName == 'POS刷卡-标准类'){
								$scope.cardServiceTypeGrid.data = [{"value":0,"sysName":"非优享"},{"value":1,"sysName":"优享"}];
								$scope.cardServiceTypeStatus = true;
							}
						})
					}else{
						$scope.cardServiceTypeGrid.data = [];
						$scope.baseInfo.optimalEnjoy = null;
						$scope.cardServiceTypeStatus = false;
					}
				}else{
					if(row.entity.sysName == 'POS刷卡-标准类'){
						$scope.cardServiceTypeGrid.data = [];
						$scope.baseInfo.optimalEnjoy = null;
						$scope.cardServiceTypeStatus = false;
					}
				}
			});
		}	
	};

	// 刷卡标准类型
	$scope.cardServiceTypeGrid = {
		columnDefs: [
			{field: 'value',displayName: '值',visible: false},
			{field: 'sysName',displayName: '刷卡标准类类型'}
		],
		onRegisterApi : function(gridApi) {
			$scope.cardServiceTypeGridApi = gridApi;
			//行选中事件
			$scope.cardServiceTypeGridApi.selection.on.rowSelectionChanged($scope,function(row,event){

			});
		}
	};

	//发卡行
	$scope.cardBinGrid = {
	        columnDefs: [
	             {field: 'bank_name',displayName: '银行名称'},
	        ],
			onRegisterApi : function(gridApi) {
				$scope.cardBinGridApi = gridApi;
			}
	};

	//行业
	$scope.acqMerchantGrid = {
		columnDefs: [
			{field: 'sysName',displayName: '行业'},
		],
		onRegisterApi : function(gridApi) {
			$scope.acqMerchantGridApi = gridApi;
		}
	};
	
	$scope.serviceTypes=[];
	$scope.submit = function(){
		//判断日期大小、金额大小
		if($scope.baseInfo.startDate>$scope.baseInfo.endDate){
			$scope.notice("开始生效日期不能大于截止生效日期");
			return false;
		}
		if($scope.baseInfo.startTime>$scope.baseInfo.endTime){
			$scope.notice("每天生效时间不能大于每天截止时间");	
			return false;
		}
		if(Number($scope.baseInfo.minTransAmount)>Number($scope.baseInfo.maxTransAmount)){
			$scope.notice("交易最小金额不能大于最大金额");
			return false;
		}
		$scope.baseInfo.weekList = [];
		addWeekDays($scope.baseInfo.weekList,$scope.baseInfo.monday);
		addWeekDays($scope.baseInfo.weekList,$scope.baseInfo.tuesday);
		addWeekDays($scope.baseInfo.weekList,$scope.baseInfo.wednesday);
		addWeekDays($scope.baseInfo.weekList,$scope.baseInfo.thursday);
		addWeekDays($scope.baseInfo.weekList,$scope.baseInfo.friday);
		addWeekDays($scope.baseInfo.weekList,$scope.baseInfo.saturday);
		addWeekDays($scope.baseInfo.weekList,$scope.baseInfo.sunday);
		if($scope.baseInfo.weekList.length==0){
			$scope.notice("请设置每周重复");
		}
		$scope.baseInfo.weekDays = $scope.baseInfo.weekList.toString();
		//取到所有需要提交的数据
		angular.forEach($scope.serviceTypeGridApi.selection.getSelectedRows(),function(item,index){
			$scope.serviceTypes[index] = item.sysValue;
		})

		$scope.cardServiceType = [];
		angular.forEach($scope.cardServiceTypeGridApi.selection.getSelectedRows(),function(item,index){
			$scope.cardServiceType.push(item.value);
		})

		var dataProvinceArray = [];
		var dataProvinceStr = "0";
		var dataCityStr = "0";

		$("#provinceCity-treeMultiselect option:selected").each(function(){
			dataProvinceArray.push($(this).attr("data-section"));
		})

		if (dataProvinceArray != null && dataProvinceArray.length > 0) {
			var dataProvinceList = Array.from(new Set(dataProvinceArray));
			dataProvinceStr = dataProvinceList.join(",");
		}

		var dataCityList = $("#provinceCity-treeMultiselect").val();
		if (dataCityList != null && dataCityList.length > 0) {
			dataCityStr = dataCityList.join(",");
		}

		if($scope.accountAddressGrid.data){
			var accountAddressArr = [];
			for(i=0; i<$scope.accountAddressGrid.data.length; i++){
				$scope.accountAddressGrid.data[i].no = i;
				accountAddressArr.push($scope.accountAddressGrid.data[i].registerAddress);
			}
			for (var i = 0; i < accountAddressArr.length; i++) {
				if(accountAddressArr.indexOf(accountAddressArr[i]) != i) {
					$scope.notice("不允许添加重复的商户注册地:"+accountAddressArr[i]);
					return ;
				}
			}
		}

		$scope.submitData = {
				baseInfo:$scope.baseInfo,
				bpList:$scope.bpGridApi.selection.getSelectedRows(),
				provinceList:dataProvinceStr,
				cardBinList:$scope.cardBinGridApi.selection.getSelectedRows(),
			    acqMerchantList:$scope.acqMerchantGridApi.selection.getSelectedRows(),
				cityList:dataCityStr,
				serviceTypes:$scope.serviceTypes,
				optimalEnjoy:$scope.cardServiceType.toString(),
				accountAddress:$scope.accountAddressGrid.data
		};
		$scope.submitting = true;
		$http.post("jumpRoute/save.do",angular.toJson($scope.submitData)).success(function(data){
			if(data.status){
				$scope.notice(data.msg);
				$state.transitionTo('org.jumpRoute',null,{reload:true});
			} else {
				$scope.notice(data.msg);
				$scope.submitting = false;
			}
		});
	}

	function addWeekDays(weekList,day){
		if(day!=null&&day!=-1){
			weekList.push(day);
		}
		return weekList;
	}

	$scope.accountAddressGrid = {
		useExternalPagination: true,		  //开启拓展名
		columnDefs: [
			{field: 'id',displayName: 'id',width: 120,pinnable: false,sortable: false,visible:false},
			{field: 'itemsDatail',displayName: '映射地详情',width: 120,pinnable: false,sortable: false,visible:false},
			{field: 'registerAddressParent',displayName: '商户注册地父级',width: 120,pinnable: false,sortable: false,visible:false},
			{field: 'registerAddress',displayName: '商户注册地',width: 220,pinnable: false,sortable: false},
			{field: 'items',displayName: '映射地',width: 350,pinnable: false,sortable: false},
			{field: 'joinAreaPolling',displayName: '不参与地区集群轮循',width: 200,
				cellTemplate:
					'<span><switch class="switch switch-s" ng-model="row.entity.joinAreaPolling" ng-true-value="1" ng-false-value="0" ng-change="grid.appScope.joinAreaPollingSwitch(row.entity)" /></span></span>'},
			{name: 'action',displayName: '操作',width: 200,pinnedRight:true,pinnable: false,sortable: false,editable:true,cellTemplate:
					"<a class='lh30' ng-click=\"grid.appScope.accountAddressUpdate(row.entity)\" >修改</a>"}
		],
		onRegisterApi: function(gridApi) {
			$http.get('accountAddress/initMappingAddress.do').success(function(data){
				$scope.accountAddressGrid.data = data.result;
			});
		}
	};

	// $scope.query = function() {
	// 	$http.post('accountAddress/page.do',
	// 		"jumpId="+$scope.jumpId+"&pageNo="+$scope.paginationOptions.pageNo+"&pageSize="+$scope.paginationOptions.pageSize,
	// 		{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
	// 	).success(function(data){
	// 		$scope.accountAddressGrid.data = data.result;
	// 		$scope.accountAddressGrid.totalItems = data.totalCount;//总记录数
	// 	}).error(function(){
	// 	});
	// };
	// $scope.query();


	$scope.joinAreaPollingSwitch=function(entity){
		var title="";
		var status=0;
		if(entity.joinAreaPolling==false){
			title="确认参与?"
		}else{
			title="确认不参与?"
			status=1;
		}
		SweetAlert.swal({
				title:title,
				showCancelButton: true,
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "提交",
				cancelButtonText: "取消",
				closeOnConfirm: true,
				closeOnCancel: true },
			function (isConfirm) {
				if (isConfirm) {
					entity.joinAreaPolling = status;
				}else{
					$scope.callBackJoinAreaPollingSwitch(entity);
				}
			});
	};

	$scope.callBackJoinAreaPollingSwitch=function (entity) {
		if(entity.joinAreaPolling==false){
			entity.joinAreaPolling=1;
		}else{
			entity.joinAreaPolling=0;
		}
	};

	$scope.initMappingField = function(){
		$scope.allProvinceSelect = [{text:"请选择",value:""}];

		$scope.allCitySelect = [{text:"请选择",value:""}];

		$scope.accountAreaAddInfo = {registerAddressType:0,joinAreaPolling:1,province:"请选择",city:"请选择",addressMapping:[{}]};
		$scope.accountAreaAddInfo.addressMapping[0].province = "请选择";
		$scope.accountAreaAddInfo.addressMapping[0].city = "请选择";

		$scope.addressGroup = [{}];
		$scope.joinGroupPollingStatus = [{"text":"不参与","value":1},{"text":"参与","value":0}]


		$scope.allProvinceMappingSelect = [[{text:"请选择",value:""}]];

		$scope.allCityMappingSelect = [[{text:"请选择",value:""}]];

		$scope.accountAddressOperType = 0;

		$scope.oldAddressEntity = {};
	}

	$scope.initMappingField();

	$scope.getAllProvince = function(){
		//获取所有省份
		$http.get('areaInfo/getAllProvince').success(function(result){
			if(result.status) {
				if(result.data==null || result.data.length==0){
					$scope.allProvinceSelect.push({text:"请选择",value:""});
				}else{
					for(var i in result.data){
						$scope.allProvinceSelect.push({text:result.data[i].name,value:result.data[i].id});
					}
				}
			}
		});
	}
	$scope.getAllProvince();

	$scope.provinceChannge = function(){
		var province = $scope.accountAreaAddInfo.province;
		if(!province || province == "请选择"){
			$scope.accountAreaAddInfo.city = "请选择";
			$scope.allCitySelect = [];
			$scope.allCitySelect.push({text:"请选择",value:""});
		}else{
			$scope.getCity(province);
		}
	}

	$scope.getCity = function(province){
		$scope.allCitySelect = [];
		$scope.allCitySelect.push({text:"请选择",value:""});
		$scope.accountAreaAddInfo.city = "请选择";
		$http.get('areaInfo/getCityByProvince?province='+province).success(function(result){
			if(result.status) {
				if(result.data==null || result.data.length==0){
					$scope.allCitySelect.push({text:"请选择",value:""});
				}else{
					for(var i in result.data){
						$scope.allCitySelect.push({text:result.data[i].name,value:result.data[i].id});
					}
				}
			}
		});
	}




	$scope.getAllProvinceMapping = function(index){
		//获取所有省份
		$http.get('areaInfo/getAllProvince').success(function(result){
			if(result.status) {
				if(result.data==null || result.data.length==0){
					$scope.allProvinceMappingSelect[index].push({text:"请选择",value:""});
				}else{
					for(var i in result.data){
						$scope.allProvinceMappingSelect[index].push({text:result.data[i].name,value:result.data[i].id});
					}
				}
			}
		});
	}
	$scope.getAllProvinceMapping(0);

	$scope.provinceChanngeMapping = function(index){
		var province = $scope.accountAreaAddInfo.addressMapping[index].province;
		if(!province || province == "请选择"){
			$scope.accountAreaAddInfo.addressMapping[index].city = "请选择";
			$scope.allCityMappingSelect[index] = [];
			$scope.allCityMappingSelect[index].push({text:"请选择",value:""});
		}else{
			$scope.getCityMapping(province,index);
		}
	}

	$scope.getCityMapping = function(province,index){
		$scope.allCityMappingSelect[index] = [];
		$scope.allCityMappingSelect[index].push({text:"请选择",value:""});
		$scope.accountAreaAddInfo.addressMapping[index].city = "请选择";
		$http.get('areaInfo/getCityByProvince?province='+province).success(function(result){
			if(result.status) {
				if(result.data==null || result.data.length==0){
					$scope.allCityMappingSelect[index].push({text:"请选择",value:""});
				}else{
					for(var i in result.data){
						$scope.allCityMappingSelect[index].push({text:result.data[i].name,value:result.data[i].id});
					}
				}
			}
		});
	}

	$scope.addAddressGroup = function(index){
		$scope.accountAreaAddInfo.addressMapping.push({province:"请选择",city:"请选择"});

		$scope.allProvinceMappingSelect.push([{text:"请选择",value:""}]);
		$scope.allCityMappingSelect.push([{text:"请选择",value:""}]);
		$scope.getAllProvinceMapping($scope.allCityMappingSelect.length - 1);
		$scope.addressGroup.push({});
	}

	$scope.deleteAddressGroup = function(index){
		$scope.addressGroup.splice(index, 1);
		$scope.accountAreaAddInfo.addressMapping.splice(index, 1);
		$scope.allProvinceMappingSelect.splice(index, 1);
		$scope.allCityMappingSelect.splice(index, 1);
	}


	$scope.addAccountAddressMapping = function(){

		if(!$scope.accountAreaAddInfo.province || $scope.accountAreaAddInfo.province == '请选择'){
			$scope.notice("请选择账单地地址");
			return;
		}

		for(i = 0; i < $scope.accountAreaAddInfo.addressMapping.length; i++){
			var address = $scope.accountAreaAddInfo.addressMapping[i].province;
			if(address == '请选择' && i != 0){
				$scope.notice("请选择完善映射地"+(i+1)+"地址");
				return;
			}
		}


		var data = {};

		var province = $scope.accountAreaAddInfo.province;
		var city = $scope.accountAreaAddInfo.city;

		var regAddress = province;
		if(city != "请选择"){
			regAddress = city;
			data.registerAddressType = 1;
		}else{
			data.registerAddressType = 0;
		}
		data.registerAddressParent = province;
		data.registerAddress = regAddress;

		var items = [];
		var mappingAddressDetail = [];
		for(i = 0; i < $scope.accountAreaAddInfo.addressMapping.length; i++){
			var provinceMapping = $scope.accountAreaAddInfo.addressMapping[i].province;
			var cityMapping = $scope.accountAreaAddInfo.addressMapping[i].city;
			if(provinceMapping == "请选择"){
				continue;
			}
			if(cityMapping == "请选择"){
				var flag = true;
				for(x = 0; x < items.length; x++){
					if(items[x] == provinceMapping){
						flag = false;
						break;
					}
				}
				if(!flag){
					$scope.notice("请删除重复的省份("+provinceMapping+")");
					return ;
				}
				mappingAddressDetail.push({addr:provinceMapping,no:i});
				items.push(provinceMapping);		//将非单列市保存
			}else{
				var flag = true;
				for(x = 0; x < items.length; x++){
					if(items[x] == cityMapping){
						flag = false;
						break;
					}
				}
				if(!flag){
					$scope.notice("请删除重复的市("+cityMapping+")");
					return ;
				}
				mappingAddressDetail.push({addr:cityMapping,parent:provinceMapping,no:i});
				items.push(cityMapping);
			}
		}
		data.items = items;
		data.joinAreaPolling = $scope.accountAreaAddInfo.joinAreaPolling;
		data.itemsDatail = mappingAddressDetail;


		if($scope.accountAddressOperType == 1){
			for(i = 0; i < $scope.accountAddressGrid.data.length; i++){
				if($scope.accountAddressGrid.data[i].registerAddress == data.registerAddress){
					$scope.notice("不能重复添加注册地");
					return ;
				}
			}
			$scope.accountAddressGrid.data.unshift(data);
		}else{
			$scope.oldAddressEntity.registerAddressType = data.registerAddressType;
			$scope.oldAddressEntity.registerAddressParent = data.registerAddressParent;
			$scope.oldAddressEntity.registerAddress = data.registerAddress;
			$scope.oldAddressEntity.items = data.items;
			$scope.oldAddressEntity.joinAreaPolling = data.joinAreaPolling;
			$scope.oldAddressEntity.itemsDatail = data.itemsDatail;
		}
		$scope.accountAddressMappingCancel();
	};

	$scope.accountAddressMappingCancel = function(){
		$('#accountAddressAdd').modal('hide');
		$scope.initMappingField();
		$scope.getAllProvince();
		$scope.getAllProvinceMapping(0);
	}

	$scope.accountAddressShow = function(type){
		$scope.accountAddressOperType = type;
		$('#accountAddressAdd').modal('show');
	}

	//$scope.accountAreaAddInfo = {registerAddressType:0,joinAreaPolling:1,province:"请选择",city:"请选择",provinceMapping:[],cityMapping:[]};
	$scope.accountAddressUpdate = function(entity){
		$scope.oldAddressEntity = entity;
		$scope.addressGroup = [];
		$scope.accountAreaAddInfo = {addressMapping:[{}]};
		$scope.accountAreaAddInfo.joinAreaPolling = entity.joinAreaPolling;
		$scope.accountAreaAddInfo.province = entity.registerAddressParent;
		$scope.getAllProvince();
		// $scope.accountAreaAddInfo.city = "请选择";
		$scope.allCitySelect = [];
		$scope.allCitySelect.push({text:"请选择",value:""});
		$http.get('areaInfo/getCityByProvince?province='+$scope.accountAreaAddInfo.province).success(function(result){
			if(result.status) {
				if(result.data==null || result.data.length==0){
					$scope.allCitySelect.push({text:"请选择",value:""});
				}else{
					for(var i in result.data){
						$scope.allCitySelect.push({text:result.data[i].name,value:result.data[i].id});
					}
				}
				if(entity.registerAddressType == 1){
					$scope.accountAreaAddInfo.city = entity.registerAddress;
				}else{
					$scope.accountAreaAddInfo.city = "请选择";
				}
			}
		});

		//获取所有省份
		$http.get('areaInfo/getAllProvince').success(function(result){
			if(result.status) {
				for(index = 0; index < entity.itemsDatail.length; index++){
					$scope.allProvinceMappingSelect[index] = [];
					$scope.allProvinceMappingSelect[index].push({text:"请选择",value:""});
					if(result.data==null || result.data.length==0){
						// $scope.allProvinceMappingSelect[index].push({text:"请选择",value:""});
					}else{
						for(var i in result.data){
							var d = {text:result.data[i].name,value:result.data[i].id};
							$scope.allProvinceMappingSelect[index].push(d);
						}
					}
				}
			}
		});

		$scope.accountAreaAddInfo.addressMapping = [{}];
		if(typeof entity.itemsDatail == 'string'){
			entity.itemsDatail = angular.fromJson(entity.itemsDatail);
		}
		if(entity.itemsDatail.length == 0){
			$scope.addressGroup = [{}];
			$scope.accountAreaAddInfo.addressMapping[0].province = "请选择";
			$scope.accountAreaAddInfo.addressMapping[0].city = "请选择";
		}
		for(i = 0; i < entity.itemsDatail.length; i++){
			var detail = entity.itemsDatail[i];
			var addr = detail.addr;
			var parent = detail.parent;
			var no = detail.no;
			$scope.accountAreaAddInfo.addressMapping[no] = [];
			if(parent){
				$scope.accountAreaAddInfo.addressMapping[no].province = parent;
				$scope.setAddressMapping(no,parent,addr);
			}else{
				$scope.accountAreaAddInfo.addressMapping[no].province = addr;
				$scope.accountAreaAddInfo.addressMapping[no].city = "请选择";
				$scope.setAddressMapping(no,addr,"请选择");
			}
			$scope.addressGroup.push({});
		}
		$scope.accountAddressOperType = 2;
		$('#accountAddressAdd').modal('show');
	}

	$scope.setAddressMapping = function(i,province,addr){
		$http.get('areaInfo/getCityByProvince?province='+province).success(function(result){
			if(result.status) {
				$scope.allCityMappingSelect[i] = [];
				if(result.data==null || result.data.length==0){
					$scope.allCityMappingSelect[i].push({text:"请选择",value:""});
				}else{
					if(addr == "请选择"){
						$scope.allCityMappingSelect[i].push({text:"请选择",value:""});
					}
					for(var index in result.data){
						$scope.allCityMappingSelect[i].push({text:result.data[index].name,value:result.data[index].id});
					}
				}
				$scope.accountAreaAddInfo.addressMapping[i].city = addr;
			}
		});
	}


	$scope.importAMShow = function(){
		$('#importAM').modal('show');
	}

	$scope.importAMCancel = function(){
		$('#importAM').modal('hide');
	}


	//上传图片,定义控制器路径
	var uploader = $scope.uploader = new FileUploader({
		url: 'jumpRoute/addressMappingImport',
		queueLimit: 1,   //文件个数
		removeAfterUpload: true,  //上传后删除文件
		headers : {'X-CSRF-TOKEN' : $scope.csrfData}
	});
	//过滤长度，只能上传一个
	uploader.filters.push({
		name: 'isFile',
		fn: function(item, options) {
			return this.queue.length < 1;
		}
	});

	$scope.clearItems = function(){  //重新选择文件时，清空队列，达到覆盖文件的效果
		uploader.clearQueue();
	}

	//导入
	$scope.importAddressMapping=function(){
		$scope.submitting = true;
		uploader.uploadAll();//上传
		uploader.onSuccessItem = function(fileItem, response, status, headers) {//上传成功后的回调函数，在里面执行提交
			if(response.status){
				$scope.accountAddressGrid.data =response.data;
				$scope.notice(response.msg);
				$scope.importAMCancel();
			}else{
				$scope.notice(response.msg);
			}
			$scope.submitting = false;
		};
	}



});